<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <script src="../lib/index.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    canvas {
      margin: 50px auto 0;
      display: block;
      background-color: yellow;
    }
  </style>
</head>

<body>
  <canvas id="canvasId" width="400" height="400">
    此浏览器不支持canvas
  </canvas>
</body>

</html>
<script>
  const ctx = document.getElementById("canvasId");
  const gl = ctx.getContext("webgl");

  // 定义顶点着色器源码 gl_Position vec4(1.0, 0.0, 0.0, 1.0) x,y,z, w齐次坐标 （x/w,y/w,z/w）
  const VERTEX_SHADER_SOURCE = `
    attribute vec4 aPosition;
    void main() {
      // 设置顶点位置
      gl_Position = aPosition;
      // 设置点的大小
      gl_PointSize = 10.0;
    }
  `;

  // 定义片元着色器源码
  const FRAGMENT_SHADER_SOURCE = `
  precision mediump float;
    // uniform vec4 uColor;
    uniform vec2 uColor;
    // uniform float uColor;
    // 主函数
    void main() {
      // 设置片元颜色为红色 
      // gl_FragColor = uColor;
      gl_FragColor = vec4(uColor.r, uColor.g, 0.0, 1.0);
      // gl_FragColor = vec4(uColor, 0.0, 0.0, 1.0);
    }
  `;

  const program = initShader(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE);
  const aPosition = gl.getAttribLocation(program, "aPosition"); // 获取attribute变量的存储位置
  const uColor = gl.getUniformLocation(program, "uColor"); // 获取uniform变量的存储位置

  gl.uniform2f(uColor, 1.0, 1.0); // 设置uniform变量的值

  gl.vertexAttrib1f(aPosition, 0.0); // 设置attribute变量的值
  // 绘制一个点
  gl.drawArrays(gl.POINTS, 0, 1); // gl.POINTS绘制点，0表示从第0个点开始绘制，1表示绘制1个点

  const points = []
  ctx.onclick = function (ev) {
    const x = ev.clientX;
    const y = ev.clientY;
    const rect = ev.target.getBoundingClientRect();

    const domX = x - rect.left;
    const domY = y - rect.top;

    const halfWidth = ctx.offsetWidth / 2; // 获取元素ctx（canvas）的宽度的一半
    const halfHeight = ctx.offsetHeight / 2;

    const clickX = (domX - halfWidth) / halfWidth;
    const clickY = (halfHeight - domY) / halfHeight;

    points.push({
      clickX,
      clickY
    })

    for (let i = 0; i < points.length; i++) {
      gl.vertexAttrib2f(aPosition, points[i].clickX, points[i].clickY);
      gl.uniform2f(uColor, points[i].clickX, points[i].clickY); // 设置uniform变量的值
      gl.drawArrays(gl.POINTS, 0, 1);
    }
  }
</script>